package com.hq.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hq.bean.House;
import com.hq.bean.User;
import com.hq.service.HouService;
import com.hq.util.FileUploadUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class HouController {
    @Resource
    HouService houService;

    @RequestMapping("/list.do")
    public String list(@RequestParam(defaultValue = "1")Integer pageNum, Model model,
                       String hname,
                       String haddress){
        Page<Object> page = PageHelper.startPage(pageNum, 5);
        List list=houService.list(hname,haddress);
        model.addAttribute("list",list);
        model.addAttribute("hname",hname);
        model.addAttribute("haddress",haddress);
        model.addAttribute("page",page);
        return "list";
    }

    @RequestMapping("/addy.do")
    public String addy(){
        return "add";
    }
    @RequestMapping("/updy.do")
    public String updy(Integer id){
        return "upd";
    }
    @RequestMapping("/findallowner.do")
    @ResponseBody
    public Object findallowner(){
        return houService.findallowner();
    }

    @RequestMapping("/addhouse.do")
    @ResponseBody
    public int addhouse(House house, String oids, MultipartFile photo, HttpSession session){
        if(photo.getSize()>0){
            String upload = FileUploadUtil.load(session, photo, "upload");
            house.setHpic(upload);
        }
        int i=houService.addhouse(house,oids);
        return i;
    }

    @RequestMapping("/login.do")
    public String login(User user,HttpSession session){
        User login = houService.login(user);
        if(login!=null){
            session.setAttribute("user",user);
            return "redirect:/list.do";
        }else{
            return "redirect:index.jsp";
        }
    }

    @RequestMapping("/findhouse.do")
    @ResponseBody
    public House findhouse(Integer id){
        return houService.findhouse(id);
    }

    @RequestMapping("/updhouse.do")
    @ResponseBody
    public int updhouse(House house, String oids, MultipartFile photo, HttpSession session){
        if(photo.getSize()>0){
            String upload = FileUploadUtil.load(session, photo, "upload");
            house.setHpic(upload);
        }
        return houService.updhouse(house,oids);
    }

}
